package com.tim.socket;

import java.net.*;
import java.io.*;
import java.util.*;

public class ChartServer3 {
	private ServerSocket server;
	Map<Integer, Socket> socketManager = new HashMap<Integer, Socket>();
	List<Socket> sManager = new ArrayList<Socket>();

	public ChartServer3() {
	}

	// 运行服务器
	void startServer() {
		try {
			server = new ServerSocket(721);
			System.out.println("服务器套接字已创建成功！");
			while (true) {
				Socket socket = server.accept();
				System.out.println("已经与客户端连接");
				sManager.add(socket);
				System.out.println("当前客户端连结数：" + sManager.size());
				new J_Thread(socket).start();
			}
		} catch (Exception e) {
		} finally {
			try {
				server.close();
			} catch (Exception e) {
			}
		}
	}

	public static void main(String[] args) {

		ChartServer3 server = new ChartServer3();
		server.startServer();
	}

	// 与客户端进行通信的线程类
	class J_Thread extends Thread {
		// 套接字引用变量
		Socket socket;
		// 套接字输入流
		private DataInputStream reader;
		// 套接字输出流
		private DataOutputStream writer;

		// 构造函数
		J_Thread(Socket socket) {
			this.socket = socket;
		}

		public void run() {
			try {
				// 获取套接字的输入流
				reader = new DataInputStream(socket.getInputStream());
				// 获取套接字的输出流
				writer = new DataOutputStream(socket.getOutputStream());
				String msg;
				// 如果收到客户端发来的数据
				while ((msg = reader.readUTF()) != null) {
					// 向客户端发送信息
					writer.writeUTF("您的情书已经收到");
					writer.flush();
					System.out.println("来自客户端：" + msg);

				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				try {
					// 删除套接字
					sManager.remove(socket);
					// 关闭输入输出流及套接字
					if (reader != null)
						reader.close();
					if (writer != null)
						writer.close();
					if (socket != null)
						socket.close();
					reader = null;
					writer = null;
					socket = null;

					// 向屏幕输出相关信息
					System.out.println("客户端离开");
					System.out.println("当前客户端的连接数：" + sManager.size());
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}

}
